package com.wildlife.springboot.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wildlife.springboot.common.Result;
import com.wildlife.springboot.entity.FishFeature;
import com.wildlife.springboot.mapper.service.ImageUploadService;
import com.wildlife.springboot.service.IFishFeatureService;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@RestController
@RequestMapping("/fishFeature")
public class FishFeatureController {

    @Resource
    private IFishFeatureService fishFeatureService;

    @Resource
    private ImageUploadService imageUploadService;

    //新增和修改
    @PostMapping
    public Result save(@RequestBody FishFeature fishFeature){
        //新增或更新
        return Result.success(fishFeatureService.saveOrUpdate(fishFeature));
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.success(fishFeatureService.removeById(id));
    }

    @PostMapping ("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids){
        return Result.success(fishFeatureService.removeByIds(ids));
    }

    @GetMapping
    public Result findAll() {
        return Result.success(fishFeatureService.list());
    }



    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(fishFeatureService.getById(id));
    }

    @GetMapping("/chineseName/{chineseName}")
    public Result findOne(@PathVariable String chineseName) {
        QueryWrapper<FishFeature> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("chinese_name", chineseName);
        return Result.success(fishFeatureService.getOne(queryWrapper));
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String chineseName
    ) {
        QueryWrapper<FishFeature> queryWrapper = new QueryWrapper<>();
        if (!"".equals(chineseName)) {
            queryWrapper.like("chinese_name", chineseName);
        }
        return Result.success(fishFeatureService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    // 导出接口
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<FishFeature> list = fishFeatureService.list();
        // 通过工具类创建writer 写出到磁盘路径

        ExcelWriter writer = ExcelUtil.getWriter(true);
        // 自定义标题别名
        writer.addHeaderAlias("id", "ID");
        writer.addHeaderAlias("outline", "目");
        writer.addHeaderAlias("section", "科");
        writer.addHeaderAlias("chineseName", "种中文名");
        writer.addHeaderAlias("englishName", "种英文名");
        writer.addHeaderAlias("latinName", "种拉丁名");
        writer.addHeaderAlias("endemicSpecies", "是否特有种");
        writer.addHeaderAlias("maleWeight", "雄性体重/g");
        writer.addHeaderAlias("femaleWeight", "雌性体重/g");
        writer.addHeaderAlias("maleLength", "雄性体长/mm");
        writer.addHeaderAlias("femaleLength", "雌性体长/mm");
        writer.addHeaderAlias("maleMouthPeak", "雄性嘴峰/mm");
        writer.addHeaderAlias("femaleMouthPeak", "雌性嘴峰/mm");
        writer.addHeaderAlias("maleWingLength", "雄性翅长/mm");
        writer.addHeaderAlias("femaleWingLength", "雌性翅长/mm");
        writer.addHeaderAlias("maleTailLength", "雄性尾长/mm");
        writer.addHeaderAlias("femaleTailLength", "雌性尾长/mm");
        writer.addHeaderAlias("maleTarsometatarsalLength", "雄性跗蹠长/mm");
        writer.addHeaderAlias("femaleTarsometatarsalLength", "雌性跗蹠长/mm");
        writer.addHeaderAlias("diet", "食性");
        writer.addHeaderAlias("eggCount", "窝卵数");
        writer.addHeaderAlias("eggSize", "卵大小/mm");
        writer.addHeaderAlias("eggVolume", "卵体积/mm3");
        writer.addHeaderAlias("nestType", "巣型（洞巢1，开放巢2，寄生3）");
        writer.addHeaderAlias("nestSite", "巢址（1地面、2水面、3灌丛、4树冠、5岩壁）");
        writer.addHeaderAlias("clusterStatus", "集群状况（0不集群,1小群,2大群）");
        writer.addHeaderAlias("migrationStatus", "迁徙状态（留鸟(R)、夏候鸟(S)、冬候鸟(W)、旅鸟(P)、迷鸟(V)）");
        writer.addHeaderAlias("distributionMigration", "分布区及其迁徙状态");
        writer.addHeaderAlias("distributionProvince", "分布省份数");

        writer.write(list, true);

        // 设置浏览器相应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("鸟类特征", StandardCharsets.UTF_8);
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }

    // 导入接口
    // reader.addHeaderAlias(): 忽略表头的中文
    @PostMapping("/import")
    public Boolean imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        reader.addHeaderAlias("ID", "id");
        reader.addHeaderAlias("目", "outline");
        reader.addHeaderAlias("科", "section");
        reader.addHeaderAlias("种中文名", "chineseName");
        reader.addHeaderAlias("种英文名", "englishName");
        reader.addHeaderAlias("种拉丁名", "latinName");
        reader.addHeaderAlias("是否特有种", "endemicSpecies");
        reader.addHeaderAlias("雄性体重/g", "maleWeight");
        reader.addHeaderAlias("雌性体重/g", "femaleWeight");
        reader.addHeaderAlias("雄性体长/mm", "maleLength");
        reader.addHeaderAlias("雌性体长/mm", "femaleLength");
        reader.addHeaderAlias("雄性嘴峰/mm", "maleMouthPeak");
        reader.addHeaderAlias("雌性嘴峰/mm", "femaleMouthPeak");
        reader.addHeaderAlias("雄性翅长/mm", "maleWingLength");
        reader.addHeaderAlias("雌性翅长/mm", "femaleWingLength");
        reader.addHeaderAlias("雄性尾长/mm", "maleTailLength");
        reader.addHeaderAlias("雌性尾长/mm", "femaleTailLength");
        reader.addHeaderAlias("雄性跗蹠长/mm", "maleTarsometatarsalLength");
        reader.addHeaderAlias("雌性跗蹠长/mm", "femaleTarsometatarsalLength");
        reader.addHeaderAlias("食性", "diet");
        reader.addHeaderAlias("窝卵数", "eggCount");
        reader.addHeaderAlias("卵大小/mm", "eggSize");
        reader.addHeaderAlias("卵体积/mm3", "eggVolume");
        reader.addHeaderAlias("巣型（洞巢1，开放巢2，寄生3）", "nestType");
        reader.addHeaderAlias("巢址（1地面、2水面、3灌丛、4树冠、5岩壁）", "nestSite");
        reader.addHeaderAlias("集群状况（0不集群,1小群,2大群）", "clusterStatus");
        reader.addHeaderAlias("迁徙状态（留鸟(R)、夏候鸟(S)、冬候鸟(W)、旅鸟(P)、迷鸟(V)）", "migrationStatus");
        reader.addHeaderAlias("分布区及其迁徙状态", "distributionMigration");
        reader.addHeaderAlias("分布省份数", "distributionProvince");
        List<FishFeature> list = reader.readAll(FishFeature.class);
        fishFeatureService.saveBatch(list);
        return true;
    }

    // 上传图片接口
    @PostMapping("/upload")
    public Result uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            String url = imageUploadService.uploadImage(file);
            // 返回相对路径而不是完整的本地文件路径
            return Result.success(url);
        } catch (Exception e) {
            return Result.fail("上传失败");
        }
    }
}
